import { Directive, Input } from '@angular/core';
import {
  NG_VALIDATORS,
  Validator,
  AbstractControl,
  FormControl,
} from '@angular/forms';

import { fuiTranslateService } from '../../i18n/i18n.module';
import { ValidatorBase } from './validator-base';


@Directive({
  selector: '[fuiEqual], [fuiEqualPassword]',
  providers: [
    {
      provide: NG_VALIDATORS,
      useExisting: EqualValidatorDirective,
      multi: true,
    },
  ],
})
export class EqualValidatorDirective extends ValidatorBase {

  /** Value for equality checking. */
  @Input() set fuiEqual(value: string) {
    this.equalTo = value;
    this.triggerValidate();
  }

  /** Value for password equality checking. */
  @Input() set fuiEqualPassword(value: string) {
    this.errorMsg = 'fui.FORM.EQUAL_PASSWORD_ERROR';
    this.equalTo = value;
    this.triggerValidate();
  }

  equalTo: string;
  errorMsg = 'fui.FORM.EQUAL_ERROR';

  constructor(private translate: fuiTranslateService) {
    super();
  }

  validate(control: AbstractControl):  {[validator: string]: string | boolean} {
    if (control.value === this.equalTo) {
      return null;
    }

    return { fuiEqual: this.translate.translateKey(this.errorMsg) };
  }
}
